# Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
# except in compliance with the License. A copy of the License is located at
#
#    http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed on an "AS IS"
# BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under the License.

#!/bin/sh

# chkconfig:   2345 51 50
# description: Start cpulimit checker script

### BEGIN INIT INFO
# Provides:          cpulimit
# Required-Start:
# Should-Start:
# Required-Stop:
# Should-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start cpulimit checker script
# Description:       Checks and limits running Ruby processes.
### END INIT INFO

RETVAL=0
LOG_FILE="/var/log/cpulimit.log"
PID_FILE="/var/run/cpulimit.pid"
EXEC_SCRIPT="/opt/cpulimit/cpulimit.sh"

case "$1" in
    start)
	    echo "Starting cpulimit..."
        $EXEC_SCRIPT 1>"$LOG_FILE" 2>&1 &
        echo $! > "$PID_FILE"
        echo "Started cpulimit with pid $!"
        ;;
    stop)
	    echo "Stopping cpulimit..."
        kill `cat $PID_FILE`
        echo "Stopped cpulimit"
        ;;
    status)
        [ -e $PID_FILE ] && echo "Running..." || echo "Stopped..."
        exit 1
	    ;;
    restart)
        echo "Stopping cpulimit..."
        kill `cat $PID_FILE`
        echo "Stopped cpulimit"
        echo "Starting cpulimit..."
        $EXEC_SCRIPT 1>"$LOG_FILE" 2>&1 &
        echo $! > "$PID_FILE"
        echo "Started cpulimit with pid $!"
        ;;
    *)
      	echo "Usage: `cpulimit $0` start|stop|restart|status"
        exit 1
esac

exit 0